package com.zhku.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhku.base.exception.TaoTaoException;
import com.zhku.base.model.PageParams;
import com.zhku.base.model.PageResult;
import com.zhku.base.model.RestResponse;
import com.zhku.user.feignclient.CheckCodeClient;
import com.zhku.user.feignclient.ShopClient;
import com.zhku.user.feignclient.TtShop;
import com.zhku.user.mapper.TtUserMapper;
import com.zhku.user.mapper.TtUserRoleMapper;
import com.zhku.user.model.dto.Login;
import com.zhku.user.model.dto.QueryUserParamsDto;
import com.zhku.user.model.dto.UpdateUserAsShopDto;
import com.zhku.user.model.dto.UserDto;
import com.zhku.user.model.po.TtUser;
import com.zhku.user.model.po.TtUserRole;
import com.zhku.user.service.TtUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class TtUserServiceImpl extends ServiceImpl<TtUserMapper, TtUser> implements TtUserService {

    @Autowired
    TtUserMapper ttUserMapper;

    @Autowired
    TtUserRoleMapper ttUserRoleMapper;

    @Autowired
    CheckCodeClient checkCodeClient;

    @Autowired
    ShopClient shopClient;

    @Override
    public TtUser commonLogin(Login login) {
        TtUser ttUser = verifyParameter(login);
        return ttUser;
    }

    @Override
    public TtUser shopLogin(Login login) {
        TtUser ttUser = verifyParameter(login);
        String reloId = getReloId(ttUser);
        if (!"2".equals(reloId)) {
            throw new TaoTaoException("您输入的不是商家账号");
        }
        return ttUser;
    }

    @Override
    public TtUser adminLogin(Login login) {
        TtUser ttUser = verifyParameter(login);
        String reloId = getReloId(ttUser);
        if (!"1".equals(reloId)) {
            throw new TaoTaoException("您输入的不是管理端账号");
        }
        return ttUser;
    }

    @Override
    public TtUser getUserByUserId(String userId) {
        if (StringUtils.isEmpty(userId)) {
            throw new TaoTaoException("传入的用户Id不能为空");
        }
        TtUser ttUser = ttUserMapper.selectOne(new LambdaQueryWrapper<TtUser>().eq(TtUser::getId, userId));
        if (ttUser == null) {
            throw new TaoTaoException("用户信息不存在");
        }
        return ttUser;
    }

    @Transactional
    @Override
    public TtUser updateUser(TtUser ttUser) {
        String userId = ttUser.getId();
        TtUser ttUserOld = ttUserMapper.selectById(userId);
        if (ttUserOld == null) {
            throw new TaoTaoException("当前用户不存在");
        }
        ttUser.setUpdateTime(LocalDateTime.now());
        int i = ttUserMapper.updateById(ttUser);
        if (i <= 0) {
            throw new TaoTaoException("修改用户信息失败");
        }
        return ttUser;
    }

    @Transactional
    @Override
    public TtUser createUser(UserDto userDto) {
        TtUser ttUser = new TtUser();
        String username = userDto.getUsername();
        Integer count = ttUserMapper.selectCount(new LambdaQueryWrapper<TtUser>().eq(TtUser::getUsername, username));
        if (count > 0) {
            throw new TaoTaoException("当前用户名已存在");
        }
        String userId = UUID.randomUUID().toString();
        BeanUtils.copyProperties(userDto, ttUser);
        ttUser.setId(userId);
        ttUser.setStatus("1");
        ttUser.setUpdateTime(LocalDateTime.now());
        ttUser.setCreateTime(LocalDateTime.now());
        int insert = ttUserMapper.insert(ttUser);
        if (insert <= 0) {
            throw new TaoTaoException("创建用户失败");
        }
        Integer roleCount = ttUserRoleMapper.selectCount(new LambdaQueryWrapper<TtUserRole>().eq(TtUserRole::getUserId, userId));
        if (roleCount > 0){
            throw new TaoTaoException("用户关联角色表已存在");
        }
        TtUserRole ttUserRole = new TtUserRole();
        String userRoleId = UUID.randomUUID().toString();
        ttUserRole.setId(userRoleId);
        ttUserRole.setUserId(userId);
        ttUserRole.setRoleId("3");
        ttUserRole.setCreateTime(LocalDateTime.now());
        int insert1 = ttUserRoleMapper.insert(ttUserRole);
        if (insert1 <= 0) {
            throw new TaoTaoException("创建用户关联角色表失败");
        }
        return ttUser;
    }

    @Override
    public PageResult<TtUser> queryUserList(PageParams pageParams, QueryUserParamsDto queryUserParamsDto) {
        //拼装查询条件
        LambdaQueryWrapper<TtUser> queryWrapper = new LambdaQueryWrapper<>();
        //根据用户名进行模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(queryUserParamsDto.getUsername()),
                TtUser::getUsername, queryUserParamsDto.getUsername());
        //创建page分页参数对象，参数：当前页码数，每页记录数
        Page<TtUser> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        Page<TtUser> ttUserPage = ttUserMapper.selectPage(page, queryWrapper);
        List<TtUser> items = ttUserPage.getRecords();
        long counts = ttUserPage.getTotal();
        PageResult<TtUser> ttUserPageResult = new PageResult<>(items,
                counts, pageParams.getPageNo(), pageParams.getPageSize());
        return ttUserPageResult;
    }

    @Transactional
    @Override
    public void deleteUser(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new TaoTaoException("错误:传入的用户id为空");
        }
        TtUser ttUser = ttUserMapper.selectById(id);
        if (ttUser == null) {
            throw new TaoTaoException("当前用户不存在");
        }
        ttUser.setStatus("0");
        int i = ttUserMapper.updateById(ttUser);
        if (i <= 0) {
            throw new TaoTaoException("禁用用户失败");
        }
    }

    @Override
    public PageResult<TtUser> queryShopUserList(PageParams pageParams, String id) {
        if (StringUtils.isEmpty(id)) {
            throw new TaoTaoException("传入的店铺id为空");
        }
        //拼装查询条件
        LambdaQueryWrapper<TtUser> queryWrapper = new LambdaQueryWrapper<>();
        //根据店铺id进行查询
        queryWrapper.eq(TtUser::getShopId, id).eq(TtUser::getStatus,"1");
        //创建page分页参数对象，参数：当前页码数，每页记录数
        Page<TtUser> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        Page<TtUser> ttShopUserPage = ttUserMapper.selectPage(page, queryWrapper);
        List<TtUser> items = ttShopUserPage.getRecords();
        long counts = ttShopUserPage.getTotal();
        PageResult<TtUser> ttShopUserPageResult = new PageResult<>(items,
                counts, pageParams.getPageNo(), pageParams.getPageSize());
        return ttShopUserPageResult;
    }

    @Override
    public List<TtUser> queryShopUserList(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new TaoTaoException("传入的店铺id为空");
        }
        //拼装查询条件
        LambdaQueryWrapper<TtUser> queryWrapper = new LambdaQueryWrapper<>();
        //根据店铺id进行查询
        queryWrapper.eq(TtUser::getShopId, id);
        List<TtUser> ttUsers = ttUserMapper.selectList(queryWrapper);

        return ttUsers;
    }

    @Transactional
    @Override
    public TtUser updateUserShop(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new TaoTaoException("传入的用户id为空");
        }
        TtUser ttUser = ttUserMapper.selectById(id);
        if (ttUser == null) {
            throw new TaoTaoException("当前用户不存在");
        }
        ttUser.setShopId("");
        ttUser.setUpdateTime(LocalDateTime.now());
        int i = ttUserMapper.updateById(ttUser);
        if (i <= 0) {
            throw new TaoTaoException("将指定的用户所关联的店铺修改为空失败");
        }
        return ttUser;
    }

    @Transactional
    @Override
    public TtUser updateUserAsShop(UpdateUserAsShopDto dto) {
        String shopName = dto.getName();
        String userId = dto.getId();
        if (StringUtils.isEmpty(shopName)) {
            throw new TaoTaoException("传入的店铺名称为空");
        }
        if (StringUtils.isEmpty(userId)) {
            throw new TaoTaoException("传入的用户id为空");
        }
        RestResponse<TtShop> ttShopRestResponse = shopClient.shopByName(shopName);
        TtShop ttShop = ttShopRestResponse.getResult();
        if (ttShop == null) {
            throw new TaoTaoException("输入的店铺名称不存在");
        }
        TtUser ttUser = ttUserMapper.selectById(userId);
        ttUser.setShopId(ttShop.getId());
        ttUser.setUpdateTime(LocalDateTime.now());
        int i = ttUserMapper.updateById(ttUser);
        if (i <= 0) {
            throw new TaoTaoException("为用户指定店铺失败");
        }
        LambdaQueryWrapper<TtUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TtUserRole::getUserId,userId);
        TtUserRole ttUserRole = ttUserRoleMapper.selectOne(queryWrapper);
        ttUserRole.setRoleId("2");
        int i1 = ttUserRoleMapper.updateById(ttUserRole);
        if (i1 <= 0) {
            throw new TaoTaoException("修改用户角色关联表失败");
        }
        return ttUser;
    }

    @Override
    public void regainUser(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new TaoTaoException("错误:传入的用户id为空");
        }
        TtUser ttUser = ttUserMapper.selectById(id);
        if (ttUser == null) {
            throw new TaoTaoException("当前用户不存在");
        }
        ttUser.setStatus("1");
        int i = ttUserMapper.updateById(ttUser);
        if (i <= 0) {
            throw new TaoTaoException("启用用户失败");
        }
    }

    private TtUser verifyParameter(Login login) {
        String checkcode = login.getCheckcode();
        String username = login.getUsername();
        String password = login.password;
        String checkcodekey = login.getCheckcodekey();
        if (StringUtils.isEmpty(checkcode) || StringUtils.isEmpty(checkcodekey)) {
            throw new TaoTaoException("请输入验证码");
        }
        //远程调用验证码服务接口校验验证码
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if (verify == null || !verify) {
            throw new TaoTaoException("验证码输入错误");
        }
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new TaoTaoException("用户名或密码不能为空");
        }
        LambdaQueryWrapper<TtUser> queryWrapper = new LambdaQueryWrapper<TtUser>()
                .eq(TtUser::getUsername, username).eq(TtUser::getStatus, "1");
        TtUser ttUser = ttUserMapper.selectOne(queryWrapper);
        if (ttUser == null) {
            throw new TaoTaoException("账号不存在");
        }
        //账号存在，判断密码输入是否正确
        String passwordRight = ttUser.getPassword();
        if (!passwordRight.equals(password)) {
            throw new TaoTaoException("账号或密码有误");
        }
        //全部校验通过
        return ttUser;
    }

    private String getReloId(TtUser ttUser) {
        String id = ttUser.getId();
        String relo_id = ttUserMapper.selectRelo_IdByUserId(id);
        return relo_id;
    }
}
